package com.devmindset.legoframework.client.mvc.binding;

import java.util.Collection;
import java.util.Date;

import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.FormItem;

/**
 * Binding utility class for bindings
 * between various widgets and {@link BaseModel}.
 *
 * @author Ice Penov <ipenov@gmail.com>
 */
public final class Bindings {
	
	private Bindings() {}
	
	/**
	 * Binds the values from the {@link DynamicForm} to the target {@link BaseModel},
	 * using property mathching.
	 * 
	 * @param form the binding destination
	 * @param model the binding destination
	 */
	public static final void bindFormToModel(DynamicForm form, BaseModel model) {
		FormItem[] formItems = form.getFields();
		for (int i = 0; i < formItems.length; i++) {
			model.set(formItems[i].getName(), formItems[i].getValue());
		}		
	}
	
	public static final void bindModelToForm(BaseModel model, DynamicForm form) {
		Collection<String> properties = model.getPropertyNames();
		for (String property : properties) {
			if (form.getField(property) != null) {
				if (model.get(property) instanceof String) {
					form.getField(property).setValue((String) model.get(property));
				} else if (model.get(property) instanceof Integer) {
					form.getField(property).setValue((Integer) model.get(property));
				} else if (model.get(property) instanceof Double) {
					form.getField(property).setValue((Double) model.get(property));					
				} else if (model.get(property) instanceof Date) {
					form.getField(property).setValue((Date) model.get(property));					
				} else if (model.get(property) instanceof Boolean) {
					form.getField(property).setValue((Boolean) model.get(property));					
				}
			}
		}
	}

}